
import re

import fnmatch
import os
import codecs
import md5
import sys

from subprocess import call


_MD5_KEY = '@werjklert@O(*:W'
_REPLACE_IN_EXT = ( 'html', 'js', )
_JS_EXT = 'js'
_STATIC_EXTS = ( _JS_EXT, 'css', )
_SID_FILENAME = 'sid'

_DONT_RENAME = ( 'jquery', 'ZeroClipboard', 'iThing', 'mamba', 'jQRangeSlider', 'v2.js' )

_PATH_TO_YUI = "/root/yuicompressor-2.4.7.jar"

# 1 find and replace all static

replaced_static = [] # contains [ [ filename1, replaced_filename1 ], [ filename2, replaced_filename2 ] ]

def _yui_js( dir_ ):
	for root, dirnames, filenames in os.walk( dir_ ):
		for filename in fnmatch.filter( filenames, "*." + _JS_EXT ):			
			js_path = os.path.join( root, filename )
		
			if _do_touch_path( js_path ):
				call( [ 'java', '-jar', _PATH_TO_YUI, js_path, '-o', js_path ] )
				

def _get_new_filename( sid, filename ):
	return md5.md5( sid + filename ).hexdigest()


def _do_touch_path( path ):
	path_lower = path.lower()
	return all( [ ( x.lower() not in path_lower ) for x in _DONT_RENAME ] )

def _replace_static( dir_ ):
	
	# find or create sid

	result = []

	sid = "0"
	
	if os.path.exists( _SID_FILENAME ):
		f = open( _SID_FILENAME, 'r' )
		sid = f.read()
		sid = str( int( sid ) + 1 )
		f.close()
	
	with open( _SID_FILENAME, 'w' ) as f:
		f.write( sid )

	
	for ext in _STATIC_EXTS:
		for root, dirnames, filenames in os.walk( dir_ ):
			for filename in fnmatch.filter( filenames, "*." + ext ):						
				new_filename = "{0}.{1}".format( _get_new_filename( sid, filename ), ext )
				old_path = os.path.join( root, filename )
				new_path = os.path.join( root, new_filename )

				if _do_touch_path( old_path ):
					os.rename( old_path, new_path )				
					result.append( [ filename, new_filename ] )
				
	return result



if __name__ == '__main__':
	dir_ = sys.argv[ 1 ]

	_yui_js( dir_ )

	replaced_static = _replace_static( dir_ )

	matches = []

	
	for rin in _REPLACE_IN_EXT:
	
		_filter_rin = '*.{0}'.format( rin )

		for root, dirnames, filenames in os.walk( dir_ ):
			for filename in fnmatch.filter( filenames, _filter_rin ):
				# work with an html file
				full_path = os.path.join( root, filename )
		
				f = codecs.open( full_path, 'r' , 'utf-8' )
				
				content = f.read()
		
				for rs in replaced_static:
					content = content.replace( '/' + rs[ 0 ], '/' + rs[ 1 ] )
					content = content.replace( "'" + rs[ 0 ], "'" + rs[ 1 ] )
					content = content.replace( "\"" + rs[ 0 ], "\"" + rs[ 1 ] )
		
				f.close()
		
				f = codecs.open( full_path, 'w', 'utf-8' )
		
				f.write( content )
		
				f.close()

